package monitor

import (
	"time"

	"github.com/prometheus/client_golang/prometheus"
	"github.com/shirou/gopsutil/cpu"
	"github.com/shirou/gopsutil/mem"
)

// ApiCounter 统计api的调用次数
var ApiCounter = prometheus.NewCounterVec(
	prometheus.CounterOpts{
		Name: "api_access_counter",
		Help: "access count of api.",
	},
	[]string{"method", "path", "result"},
)

// GaugeVec 统计单独的指标：比如cpu使用占比
var GaugeVec = prometheus.NewGaugeVec(
	prometheus.GaugeOpts{
		Name: "gauge_vec",
	},
	[]string{"name"},
)

// HttpDurations 接口耗时统计
var HttpDurations = prometheus.NewSummaryVec(
	prometheus.SummaryOpts{
		Name:       "http_durations_seconds",
		Objectives: map[float64]float64{0.9: 0.01},
	},
	[]string{"method", "path"},
)

func Init() {
	// Metrics have to be registered to be exposed:
	prometheus.MustRegister(ApiCounter, GaugeVec, HttpDurations)
	go func() {
		for {
			time.Tick(15 * time.Second)
			// cpu使用percent
			percent, _ := cpu.Percent(time.Second, false)
			GaugeVec.WithLabelValues("cpuUsed").Set(percent[0])
			// 内存使用percent
			memInfo, _ := mem.VirtualMemory()
			GaugeVec.WithLabelValues("memoryTotal").Set(float64(memInfo.Total) / 1000_000_000)
			GaugeVec.WithLabelValues("memoryUsed").Set(memInfo.UsedPercent)
		}
	}()
}

func StopPrometheus() {
	prometheus.Unregister(ApiCounter)
	prometheus.Unregister(GaugeVec)
	prometheus.Unregister(HttpDurations)
}
